package com.lebang.service.sys;

import com.lebang.component.RedisClient;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.AdErrorConfig;
import com.lebang.domain.SdkErrorDayLog;
import com.lebang.domain.SdkErrorLog;
import com.lebang.entity.RequestHeaders;
import com.lebang.example.AdErrorConfigExample;
import com.lebang.mapper.AdErrorConfigMapper;
import com.lebang.mapper.SdkErrorDayLogMapper;
import com.lebang.mapper.SdkErrorLogMapper;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

import static com.lebang.service.DownAppService.FILTER_KEY;

/**
 * ad_error_config
 *
 * @Author hwq
 * @Date 2020-09-16
 */
@Service
public class AdErrorConfigService extends BaseService<AdErrorConfig, Integer, AdErrorConfigExample> {
    @Autowired
    private SdkErrorLogMapper sdkErrorLogMapper;
    @Autowired
    private AdErrorConfigMapper adErrorConfigMapper;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private SdkErrorDayLogMapper sdkErrorDayLogMapper;
    public static final String LOCK_KEY="lock:sdkkey:";
    public static final String ERROR_SDK_KEY="error:sdkkey:";

    public void add(String sdkKey, String errorCode, String errorMsg, String area, RequestHeaders headers) {
        if(errorMsg.length()>512){
            errorMsg=errorMsg.substring(0,511);
        }
        if(headers.getUa().length()>256){
            headers.setUa(headers.getUa().substring(0,255));
        }
        SdkErrorLog errorLog = new SdkErrorLog();
        errorLog.setUa(headers.getUa());
        errorLog.setAndroidVersion(headers.getOsVersion());
        errorLog.setCreateTime(LocalDateTime.now());
        errorLog.setMemberId(headers.getUserid());
        errorLog.setAppStore(headers.getAppStore());
        errorLog.setVersion(headers.getVersion());
        errorLog.setIpAddr(headers.getIpAddr());
        errorLog.setMacAddr(headers.getMacAddr());
        errorLog.setImei(headers.getImei());
        errorLog.setSdkKey(sdkKey);
        errorLog.setErrorCode(errorCode);
        errorLog.setErrorMsg(errorMsg);
        errorLog.setHasDeleted(0);
        errorLog.setAdId(area);
        sdkErrorLogMapper.insertSelective(errorLog);
        AdErrorConfig config = adErrorConfigMapper.selectBySdkKeyAndErrorCode(sdkKey, errorCode);
        if(!redisClient.hexists(FILTER_KEY + headers.getUserid(), sdkKey)){
            SdkErrorDayLog sdkErrorDayLog = new SdkErrorDayLog();
            sdkErrorDayLog.setCreateTime(LocalDateTime.now());
            sdkErrorDayLog.setMemberId(headers.getUserid());
            sdkErrorDayLog.setAppStore(headers.getAppStore());
            sdkErrorDayLog.setVersion(headers.getVersion());
            sdkErrorDayLog.setIpAddr(headers.getIpAddr());
            sdkErrorDayLog.setMacAddr(headers.getMacAddr());
            sdkErrorDayLog.setImei(headers.getImei());
            sdkErrorDayLog.setSdkKey(sdkKey);
            sdkErrorDayLog.setErrorCode(errorCode);
            sdkErrorDayLog.setErrorMsg(errorMsg);
            sdkErrorDayLog.setHasDeleted(0);
            sdkErrorDayLog.setAdId(area);
            sdkErrorDayLog.setCreateDate(LocalDate.now());
            sdkErrorDayLogMapper.insertSelective(sdkErrorDayLog);

            if(config!=null){
                //当天用户数据源上报错误的次数
                Integer count = sdkErrorDayLogMapper.countByMemberIdAndSdkKey(headers.getUserid(),sdkKey,LocalDate.now());
                //容错次数
                Integer faultTimes = config.getFaultTimes();
                //判断是否达到容错次数
                if(count%faultTimes==0){
                    //达到容错次数,进入封禁状态
                    Integer time = 0;
                    int times = count/faultTimes;
                    //判断第几次进入封禁状态
                    if(times==1){
                        time = config.getWaitTime();
                    }else if(times==2){
                        time = config.getSecondWaitTime();
                    }else if(times>2){
                        time = config.getMoreWaitTime();
                    }
                    redisClient.hset(FILTER_KEY + headers.getUserid(), sdkKey, String.valueOf(System.currentTimeMillis() + time * 60000));
                    redisClient.setex(LOCK_KEY+headers.getUserid() + sdkKey, sdkKey, time * 60);
                }
            }
        }
        //今日错误码的数量+1
        String nowDateString = LocalDate.now().format(DateTimeFormatter.ISO_DATE);
        redisClient.hincrby(ERROR_SDK_KEY+nowDateString,sdkKey+":"+errorCode,1L);
        if (!redisClient.exists(sdkKey+":"+errorCode)){
            redisClient.set(sdkKey+":"+errorCode,errorMsg);
        }



    }

    public AdErrorConfig selectBySdkKeyAndErrorCode(String sdkKey,String errorCode){
      return   adErrorConfigMapper.selectBySdkKeyAndErrorCode(sdkKey, errorCode);
    }
    @DataSource("commonDB")
    public void insert(AdErrorConfig adErrorConfig) {
        adErrorConfigMapper.insertSelective(adErrorConfig);
    }
}
